import {defineStore} from 'pinia'
import {ref} from 'vue'
import {getUInfo} from '@/api/user'
import {SUCCESS} from "@/core/constants/HttpStatus";
import {ElMessage} from "element-plus";
import {useMessageStore} from "@/store";


//用户模块：token setToken removeToken
export const useUserStore = defineStore('user-token', () => {
        const token = ref('')
        const setToken = (newToken) => {
            token.value = newToken;
        }
        const removeToken = () => {
            token.value = ''
        }

        const userInfo = ref({})
        const setUserInfo = (value) => {
            userInfo.value = value;
        }
        const fetchUserInfo = async () => {
            const res = await getUInfo();
            // console.log(res.data);
            const {code, data, msg} = res.data;
            if (code != SUCCESS) {
                setUserInfo(null)
                setToken('');
                return false;
            }
            setUserInfo(data);
            const {getNewMessageState} = useMessageStore();
            await getNewMessageState();
            return true;
        }
        const removeData = () => {
            token.value = ''
            userInfo.value = {}
            // todo: 消息状态清空
        }
        return {
            token,
            setToken,
            removeToken,
            userInfo,
            fetchUserInfo,
            removeData
        }
    },
    {//持久化配置
        persist: true
    })
